import json

def load_data_from_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        data = json.load(file)
    return data

def find_recent_decline(data, decline_days=3):
    stock_prices = {}
    all_dates = sorted({day["trandt"] for day in data}, reverse=True)

    # 获取最近指定天数天的交易日期
    recent_dates = all_dates[:decline_days]

    # 组织数据，以股票代码为键，存储每个日期的收盘价
    for day in data:
        date = day["trandt"]
        if date not in recent_dates:
            continue
        for stock in day["data"]["diff"]:
            stock_code = stock["f12"]
            close_price = stock["f2"]

            if stock_code not in stock_prices:
                stock_prices[stock_code] = {}

            stock_prices[stock_code][date] = close_price

    # 找出在最近指定天数内连续下跌的股票
    declining_stocks = []
    for stock_code, prices in stock_prices.items():
        if all(date in prices for date in recent_dates):
            is_declining = True
            for i in range(decline_days - 1):
                if prices[recent_dates[i]] <= prices[recent_dates[i + 1]]:
                    is_declining = False
                    break
            if is_declining:
                declining_stocks.append({
                    "stock_code": stock_code,
                    "dates": recent_dates,
                    "prices": [prices[date] for date in recent_dates]
                })

    return declining_stocks

# 读取数据文件
file_path = '/Users/macbookair/workspace/pythonlearning/01test/tiantianjijin/all_processed_data.json'
data = load_data_from_file(file_path)

# 查找连跌4天或5天的股票
recent_four_day_declines = find_recent_decline(data, decline_days=4)
recent_five_day_declines = find_recent_decline(data, decline_days=5)

# 输出连跌4天的股票结果
print("连跌4天的股票:")
for decline in recent_four_day_declines:
    print(f"股票代码: {decline['stock_code']}")
    print(f"日期: {decline['dates']}")
    print(f"价格: {decline['prices']}")
    print()

# 输出连跌5天的股票结果
print("连跌5天的股票:")
for decline in recent_five_day_declines:
    print(f"股票代码: {decline['stock_code']}")
    print(f"日期: {decline['dates']}")
    print(f"价格: {decline['prices']}")
    print()
